#ifndef DEXTEROUS_HAND_H
#define DEXTEROUS_HAND_H

#include "protocol.h"
#include "packet.h"
#include "serial/serial.h"
#include <memory>
#include <thread>
#include <atomic>
#include <chrono>
#include <functional>
#include <mutex>

class DexterousHand {
public:
    // 构造函数
    DexterousHand(const std::string& port, unsigned long baud = 2000000);
    
    // 析构函数
    ~DexterousHand();
    
    // 初始化连接
    bool initialize();
    
    // 关闭连接
    void close();
    
    // 设置灵巧手ID
    void setHandId(uint8_t hand_id) { hand_id_ = hand_id | 0x80; }
    
    // 开始实时控制
    bool startRealTimeControl(int frequency_hz = 83);
    
    // 停止实时控制
    void stopRealTimeControl();
    
    // 设置关节控制参数
    void setJointParams(int joint_id, const JointParamsDownlink& params);
    
    // 获取关节状态
    JointParamsUplink getJointStatus(int joint_id) const;
    
    // 获取传感器数据
    SensorParam getSensorData(int sensor_id) const;
    
    // 获取灵巧手参数
    bool getHandParameters(UserData& user_data);
    
    // 获取最新状态（新增）
    RS485Uplink getHandStatus() const;
    
    // 设置状态回调函数
    void setStatusCallback(std::function<void(const RS485Uplink&)> callback);
    
    // 获取连接状态
    bool isConnected() const { return connected_.load(); }
    
    // 获取当前时间字符串
    static std::string getCurrentTimeString();

private:
    // 串口通信
    std::unique_ptr<serial::Serial> serial_;
    std::string port_;
    unsigned long baud_;
    
    // 连接状态
    std::atomic<bool> connected_{false};
    std::atomic<bool> real_time_running_{false};
    
    // 数据缓存
    RS485Downlink downlink_data_;
    RS485Uplink uplink_data_;
    mutable std::mutex data_mutex_;
    
    // 实时控制线程
    std::unique_ptr<std::thread> real_time_thread_;
    int control_frequency_;
    
    // 状态回调
    std::function<void(const RS485Uplink&)> status_callback_;
    
    // 设备地址
    uint8_t hand_id_{0x80};
    
    // 私有方法
    void realTimeControlLoop();
    bool sendCommand(uint8_t cmd, const void* data = nullptr, uint16_t data_len = 0);
    bool receiveResponse(uint8_t expected_cmd, std::vector<uint8_t>& response_data, 
                        int timeout_ms = 1000);
    void processReceivedData();
};

#endif // DEXTEROUS_HAND_H